{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-06-25T07:06:00.050833Z",
     "start_time": "2025-06-25T07:06:00.039248Z"
    }
   },
   "source": [
    "from datetime import datetime\n",
    "\n",
    "from langchain.agents import Tool, create_react_agent, AgentExecutor\n",
    "from langchain_core.tools import tool\n",
    "from langchain_ollama import OllamaLLM\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "from jupyter_constants import OLLAMA_DEFAULT_MODEL\n",
    "from tool_call.ollama_prompt import TOOL_CALL_TEMPLATE"
   ],
   "outputs": [],
   "execution_count": 39
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-25T07:06:00.079177Z",
     "start_time": "2025-06-25T07:06:00.071003Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Step 1-1: Define a function to get the current time\n",
    "def get_current_time(*args, **kwargs):\n",
    "    \"\"\"Return the current time\"\"\"\n",
    "    now = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n",
    "    return f\"The current time is: {now}\""
   ],
   "id": "8ecee8bd35f11c43",
   "outputs": [],
   "execution_count": 40
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-25T07:06:00.098486Z",
     "start_time": "2025-06-25T07:06:00.086685Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Step 1-2: Define a function to get whether information use a different approach.\n",
    "@tool\n",
    "def get_weather(city: str) -> str:\n",
    "    \"\"\"返回指定城市的当前天气情况（模拟数据）\"\"\"\n",
    "    weather_data = {\n",
    "        \"北京\": \"晴天，25°C\",\n",
    "        \"上海\": \"多云，28°C\",\n",
    "        \"广州\": \"雷阵雨，30°C\"\n",
    "    }\n",
    "    return weather_data.get(city, \"未知城市或无数据\")"
   ],
   "id": "ab9658318f5be37",
   "outputs": [],
   "execution_count": 41
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-25T07:06:00.115652Z",
     "start_time": "2025-06-25T07:06:00.102614Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Step 2: Create LangChain tools\n",
    "tools = [\n",
    "    Tool(\n",
    "        name=\"GetCurrentTime\",\n",
    "        func=get_current_time,\n",
    "        description=\"You can use this tool_call when you need to know the current time.\",\n",
    "    ),\n",
    "    get_weather\n",
    "]"
   ],
   "id": "e808f456c672ca35",
   "outputs": [],
   "execution_count": 42
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-25T07:06:00.898129Z",
     "start_time": "2025-06-25T07:06:00.118180Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Step 3: Initialize the local Ollama model\n",
    "llm = OllamaLLM(model=OLLAMA_DEFAULT_MODEL)  # Make sure you've pulled this model locally"
   ],
   "id": "3f8bb4bb8628aac4",
   "outputs": [],
   "execution_count": 43
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-25T07:06:00.909644Z",
     "start_time": "2025-06-25T07:06:00.898129Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Step 4: Define a prompt for the ReAct agent (with all required variables)\n",
    "prompt = PromptTemplate.from_template(TOOL_CALL_TEMPLATE)"
   ],
   "id": "d5dde90fc9d8cdb3",
   "outputs": [],
   "execution_count": 44
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-25T07:06:00.925438Z",
     "start_time": "2025-06-25T07:06:00.909644Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Step 5: Create and initialize the agent\n",
    "agent = create_react_agent(llm, tools, prompt)\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ],
   "id": "a6df459f068be0c4",
   "outputs": [],
   "execution_count": 45
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-25T07:06:00.938553Z",
     "start_time": "2025-06-25T07:06:00.925438Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def run_agent(query):\n",
    "    print(f\"User input question: {query}\")\n",
    "    response = agent_executor.invoke({\n",
    "        \"input\": query\n",
    "    })\n",
    "    print(\"回答：\", response[\"output\"])"
   ],
   "id": "a7adf5f16a71f608",
   "outputs": [],
   "execution_count": 46
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-25T07:11:10.138481Z",
     "start_time": "2025-06-25T07:06:00.941157Z"
    }
   },
   "cell_type": "code",
   "source": [
    "if __name__ == \"__main__\":\n",
    "    print(\"欢迎使用 LangChain + Ollama Tool Call 示例\")\n",
    "    while True:\n",
    "        user_input = input(\"\\n请输入问题（输入 'exit' 退出）：\")\n",
    "        if user_input.lower() in [\"exit\", \"quit\"]:\n",
    "            break\n",
    "        run_agent(user_input)"
   ],
   "id": "79b2dc24ab4493d4",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "欢迎使用 LangChain + Ollama Tool Call 示例\n",
      "User input question: 现在几点？\n",
      "\n",
      "\n",
      "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
      "\u001B[32;1m\u001B[1;3m<think>\n",
      "\n",
      "</think>\n",
      "\n",
      "Thought: 我需要知道当前的时间。\n",
      "Action: GetCurrentTime\n",
      "Action Input: \u001B[0m\u001B[36;1m\u001B[1;3mThe current time is: 2025-06-25 15:06:16\u001B[0m\u001B[32;1m\u001B[1;3m<think>\n",
      "\n",
      "</think>\n",
      "\n",
      "Final Answer: 现在是15点06分。\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n",
      "回答： 现在是15点06分。\n",
      "User input question: 今天北京的天气如何？\n",
      "\n",
      "\n",
      "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
      "\u001B[32;1m\u001B[1;3m<think>\n",
      "\n",
      "</think>\n",
      "\n",
      "Thought: 我需要先获取当前时间，然后根据时间判断是否需要获取天气信息。不过，用户直接询问的是天气，所以我可以直接调用 get_weather 工具。\n",
      "Action: get_weather\n",
      "Action Input: 北京\u001B[0m\u001B[33;1m\u001B[1;3m晴天，25°C\u001B[0m\u001B[32;1m\u001B[1;3m<think>\n",
      "\n",
      "</think>\n",
      "\n",
      "Final Answer: 今天北京的天气是晴天，气温25°C。\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n",
      "回答： 今天北京的天气是晴天，气温25°C。\n"
     ]
    }
   ],
   "execution_count": 47
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
